<template>
    <view>
        <cu-custom bgColor="bg-white" :isBack="true"><block slot="content" class="text-000 text-black" style="overflow:hidden;text-overflow:ellipsis" >{{options.cinema_name ? options.cinema_name:''}}选座</block></cu-custom>
        <view class="bg-f1 h-100vh position-relative">
            <view class="pt-f left-0 w-100 p-0-32 bg-white z1000 padding-bottom-sm flex justify-between align-center">
                <view>
                    <view class="text-df text-000 fw-b pt-20" v-if="seatInfo">
                        {{seatInfo.show.show_name}}
                    </view>
                    <view class="mt-10 fz-28 color-666" v-if="seatInfo">
                        {{seatInfo.mark}}
                    </view>
                </view>
                <view>
                    <text class="text-blue" @tap="changeSchedule">更换场次</text><text class="cuIcon-unfold margin-left-xxs"></text>
                </view>
            </view>

            <view class="w-100">
                <movable-area :style="'height:'+(seatRow*40+350)+'rpx;width: 100vw;top:'+(rpxNum*132+95)+'px;'" class="pt-f left-0">
                    <movable-view :style="'width: 100vw;height:'+(seatRow*40+350)+'rpx;'" :inertia="true" :scale="true" :scale-min="0.95"
                                  :scale-max="2" direction="all" @change="onMove" @scale="onScale">
<!--                     选项小图标-->
                      <view class="dp-f jc-c ai-c mb-20 text-gray text-sm margin-bottom-lg" v-if="showTis">
                        <view class="dp-f jc-c ai-c m-0-10">
                          <!--                            <img :style="'width:'+seatSize+'px;height:'+seatSize+'px'" mode="aspectFit" /><span class="ml-10">可选</span>-->
                          <text class="iconfont icon-select margin-top-xs ml-10">可选</text>
                        </view>
                        <view class="dp-f jc-c ai-c m-0-10">
                          <!--                            <img :style="'width:'+seatSize+'px;height:'+seatSize+'px'" :src="$tools.j('bought_1.png')" mode="aspectFit"/><span class="ml-10">不可选</span>-->
                          <text class="iconfont icon-select margin-top-xs ml-10 text-green "><text class="text-gray">已选</text></text>
                        </view>
                        <view class="dp-f jc-c ai-c m-0-10">
                          <!--                            <img :style="'width:'+seatSize+'px;height:'+seatSize+'px'" :src="$tools.j('selected_1.png')" mode="aspectFit"/><span class="ml-10">选中</span>-->
                          <text class="iconfont icon-select margin-top-xs ml-10 text-red "><text class="text-gray">已售</text></text>
                        </view>
                      </view>
<!--                      中间选座区域-->
                        <view class="text-center  text-gray  response">
                            <view class="margin-tb-xs text-df">激光厅-请配带口罩</view>
                            <view  class="margin-top-sm" :style="'width:80%;margin:0 auto;height:40rpx;background: url('+$tools.j('jg_bg_small.png')+') no-repeat center;background-size:cover;'"></view>
                        </view>

                        <!--<view class="Stage dp-f jc-c ai-c fz-22 color-333">
                            激光厅
                        </view>-->
<!--                        <view style="width: 100rpx;height: 30rpx;" class="m-0-a margin-top-sm dp-f jc-c ai-c text-xs color-999 b-1 br-5 margin-bottom">银幕中央</view>-->
                        <view class="position-relative margin-top">
                            <!--中间虚线开始-->
                            <view class="position-absolute pa-v-2 b-d-1" :style="'height:'+seatRow*(20+seatSize*pxNum)+'rpx;top:-10rpx;width:0'"></view>
                            <!--/中间虚线结束-->
                            <view>
                                <view v-for="(item,index) in seatArray" :key="index" class="dp-f jc-c mt-20" :style="'width:'+boxWidth+'px;height:'+seatSize+'px'">
                                    <view v-for="(seat,col) in item" :key="col" class="dp-ib" :style="'width:'+seatSize+'px;height:'+seatSize+'px'"
                                          @click="handleChooseSeat(index,col)">
                                        <img v-if="seat.type===0" class="w-100 h-100"      :src="$tools.j('unselected_1.png')"    mode="aspectFit" />
                                        <img v-else-if="seat.type===1" class="w-100 h-100" :src="$tools.j('selected_1.png')" mode="aspectFit" />
                                        <img v-else-if="seat.type===2" class="w-100 h-100" :src="$tools.j('bought_1.png')"   mode="aspectFit" />
                                    </view>
                                </view>
                            </view>
                            <view class="position-absolute bg-line br-15 over-h" :style="'left: '+(10-moveX/scale)+'px;top:-20rpx;width:30rpx;'">
                                <view class="w-100 dp-f ai-c jc-c fz-22 color-fff" :style="'height:'+seatSize+'px;margin-top:20rpx;'" v-for="(m,mindex) in mArr"
                                      :key="mindex">{{m}}</view>
                                <view :style="'height: 20rpx;'"></view>
                            </view>
                        </view>


                    </movable-view>
                </movable-area>
                <view class="pt-f bottom-bar left-0 dp-f fd-cr z1000">
                    <view class="bg-white padding-sm">
                        <!--<view class="dp-f ai-c jc-c fz-28 color-333 mb-20" v-if="SelectNum===0">
                            推荐选座
                            <view style="width: 106rpx;height: 60rpx;" class="b-1 br-5 dp-f ai-c jc-c fz-28 ml-20" v-for="(n,numindex) in 4"
                                  :key="n" @click="smartChoose(numindex+1)">
                                {{numindex+1}}人
                            </view>
                        </view>-->
                        <view class="paddding" v-if="SelectNum>0">
                            <view class="margin-bottom-sm text-black">已选座位</view>
                            <view class="text-center" style="display: grid;grid-template-columns: repeat(4, 24%);grid-gap: 10rpx;">
<!--                              已选座位-->
                                <view  class="padding-lr-xs padding-tb-xs flex justify-between align-center radius-lg bg-gray margin-right-xs margin-bottom-sm" v-for="(optItem,optindex) in optArr" :key="optindex">
                                    <view>
                                        <!--数字行-->
                                        <text v-if="!characterRow">{{optItem.RowNum+'排'+optItem.ColumnNum+'座'}}</text>
                                        <!--字母行-->
                                        <text v-if="characterRow">{{characterData[optItem.RowNum-1]+'排'+optItem.ColumnNum+'座'}}</text>

                                        <view v-if="optItem.flag===1" class="text-xs text-gray">情侣座(左)</view>
                                        <view v-if="optItem.flag===2" class="text-xs text-gray">情侣座(右)</view>
                                        <view class="text-red text-sm text-gray" style="text-decoration:line-through">￥34</view>
                                        <view class="text-red text-sm">￥{{optItem.price}}</view>
                                    </view>
                                    <view class="cuIcon-close text-gray" @tap="handleChooseSeat(optItem.RowNum-1,optItem.columInex)"></view>
                                </view>
                            </view>
                        </view>
                        <!--<view class="dp-f ai-c fw-w fz-28 color-333 mb-20" v-if="SelectNum>0">
                            <text>已选</text>
                            <view class="p-all-10 b-1 br-5 dp-f ai-c jc-c fz-28 ml-20" v-for="(optItem,optindex) in optArr" :key="optindex">
                                {{optItem.RowNum+'排'+optItem.ColumnNum+'座'}}
                            </view>
                        </view>-->
                      <view class="flex justify-between">
                        <view class="margin-bottom-sm padding-left-xs">
                          <view class="text-black text-bold">无座自动备选</view>
                          <view class="text-gray text-sm margin-top-xs">当您选择的座位已出售时，影院为您选择最佳观影座位。</view>
                        </view>
                        <view class="align-center flex justify-center">
                          <switch></switch>
                        </view>
                      </view>
                        <view style="width: 710rpx;height: 80rpx;" class="dp-f jc-c ai-c fz-34 color-fff radius-xxxl" :class="SelectNum>0?'bg-red-1':'bg-unbtn'"
                              @click="buySeat">
                          <text class="text-white margin-top-xxs margin-right-xs" style="text-decoration:line-through">
                            {{ SelectNum>0?('34'):'' }}</text>
                          {{SelectNum>0?('现价'+aPrice+'元 立即购买'):'请先选座'}}
                        </view>
                    </view>

                </view>
            </view>
        </view>
        <!--授权登录-->
        <authorize      ref="authorize"       @loginOk="loginOk"/>
        <!--授权手机号-->
        <AuthorizePhone ref="authorizePhone"  @authorizePhoneOk="authorizePhoneOk"/>
        <!--排期-->
        <changeSchedule ref="changeScheduleRef" :schedules="seatInfo.schedules" @confirm="changeScheduleConfirm" :sid="options.sid"/>
    </view>
</template>
<script>
    import authorize         from '@/components/authorize/Authorize'
    import AuthorizePhone    from '@/components/authorize/AuthorizePhone'
    import changeSchedule    from './components/changeSchedule'
    export default {
        data() {
            return {
                options:'',
                CustomBar: this.CustomBar+5,
                scaleMin:1,//h5端为解决1无法缩小问题，设为0.95
                boxWidth: 400, //屏幕宽度px
                space: ' ', //空格
                seatArray: [], //影院座位的二维数组,-1为非座位，0为未购座位，1为已选座位(绿色),2为已购座位(红色),一维行，二维列
                seatRow: 0, //影院座位行数
                seatCol: 0, //影院座位列数
                seatSize: 0, //座位尺寸
                SelectNum: 0, //选择座位数
                moveX: 0, //水平移动偏移量
                scale: 1, //放大倍数
                minRow: 0, //从第几行开始排座位
                minCol: 0, //从第几列开始排座位
                showTis: true, //显示选座提示
                seatList: [], //接口获取的原始位置
                mArr: [], //排数提示
                optArr: [], //选中的座位数组。
                maxCanBuy:4,// 默认最多选择4个
                isWXAPP:false,
                seatInfo:'',
                characterRow:false,
                characterData:[...Array(26).keys()].map(i => String.fromCharCode(i + 65)),
            };
        },
        components:{
            authorize,AuthorizePhone,changeSchedule
        },
        computed: {
            //分为单位
            aPrice(){
                if(this.SelectNum>0){
                    let num = this.optArr.reduce((price,item)=>{
                        return  price +=item.price
                    },0)
					return num.toFixed(2)
                }else{
                    return 0;
                }

            },
            rpxNum() {
                return this.boxWidth / 750
            },
            pxNum() {
                return 750 / this.boxWidth
            },
        },
        onLoad(options) {
            //获取宽度
            this.init(options)
        },
        methods: {
            async init(options){
                this.options = options

                this.$thirdApi.getSystemInfo().then(res=>{
                    if(res){
                        this.boxWidth = res.screenWidth
                        //#ifdef H5
                        this.scaleMin = 0.95
                        //#endif
                    }
                })
                this.initData()

                console.log('初始化用户登录所需sesssion_key')
                this.$user.wx_login_info()
            },
            async initData(){
                //获取当前座位信息
                let prarams = {scheduleId:this.options.sid,show_id:this.options.show_id,cinema_id:this.options.cinema_id}
                if(this.options.show_date) prarams = Object.assign(prarams,{show_date:this.options.show_date})
                let res = await this.$api.seat(prarams);
                console.log('获取当前座位信息');
                console.log(res.data);
                this.seatInfo  = res.data
                this.maxCanBuy = res.data.list.maxCanBuy
                //找最大值和行数
                let temp =[];
                let temp1=[];
                const setColumnSet = new Set();
                res.data.list.seats.forEach((v,k)=>{
                    let rowColumn = v.name.match(/\w+/g);
                    // console.log(rowColumn)
                    //console.log(v.name)
                    //console.log(rowColumn)

                    let RowNum;
                    //正常数字的情况下
                    if(!isNaN(parseInt(rowColumn[0]))){
                        RowNum = parseInt(rowColumn[0])
                    }else{

                        // console.log('characterData')
                        // console.log('26个字母情况')
                        //以字母标记的行
                        this.characterRow = true
                        RowNum =  this.characterData.findIndex(v=>v===rowColumn[0])+1;
                        //console.log(RowNum)
                        //console.log('RowNum 结束......')
                    }
                    let ColumnNum = parseInt(rowColumn[1])
                    if(!temp[RowNum]) {
                        temp[RowNum]=[];temp1[RowNum]=[]
                    }
                    setColumnSet.add(ColumnNum)
                    temp[RowNum].push(ColumnNum)
                    temp1[RowNum].push(v)
                })

                // console.log('temp')
                // console.log(temp)
                // console.log('temp1')
                // console.log(temp1)
                // console.log('最大的列数')
                // console.log(Math.max(...setColumnSet))
                let maxColumnNumber = Math.max(...setColumnSet)
                let oKPoint={};

                let keys = [...temp.keys()];

                // console.log('temp.keys()');
                // console.log(keys);

                let temp_compare = temp.filter(v=>v)

                // console.log('temp_compare')
                // console.log(temp_compare)
                //正序
                if(temp_compare[0][0]<temp_compare[0][1]){
                    //console.log('正序。。。。。:'+temp_compare[0][0])
                    for(let x=1 ;x<=maxColumnNumber;x++){
                        //第一个 X坐标 从10开始
                        oKPoint[x]= 9 + x;
                    }
                }else{
                   //   console.log('倒序。。。。。'+temp_compare[0][0])
                    //倒序
                    for(let x=1 ;x<=maxColumnNumber;x++){
                        //第一个从10开始
                        oKPoint[maxColumnNumber-x+1]= 9 + x;
                    }
                }
                  // console.log('oKPoint')
                  // console.log(oKPoint)

                let initArr=[]

                temp.forEach((v,k)=> {
                    if (k>0) {
                        // console.log('line:'+k);
                        v.forEach((v1, k1) => {
                            // console.log('num:'+v1);

                            let YCoord=2+k; //Y坐标 3开始
                            let XCoord=oKPoint[v1]; //X坐标
                            //座位状态:1:可售，0:不可售，-1:删除(非法)
                            //status 0为未购座位，1为已选座位(绿色),2为已购座位(红色)
                            let status
                            switch (temp1[k][k1]['status']) {
                                case 0:
                                    status = 1;
                                    break;
                                case 1:
                                    status = 0;
                                    break;
                                default:
                                    status = temp1[k][k1]['status'];
                                    break;
                            }
                            initArr.push({
                                "YCoord"   : YCoord,
                                "XCoord"   : XCoord,
                                "SeatCode" : temp1[k][k1]['extId'],
                                "Status"   : status,
                                "RowNum"   : k,
                                "ColumnNum": v1,
                                "name"     : temp1[k][k1]['name'],
                                "flag"     : temp1[k][k1]['flag'],  //flag=0  普通座 flag=1 左边情侣座 flag=2 右边情侣座
                                "price"    : temp1[k][k1]['price'],
                                "areaId"   : temp1[k][k1]['area']>=0 ? temp1[k][k1]['area'] : 0,
                            })

                        })
                    }

                })

                // console.log('最终的数组是:');
                //   console.log(JSON.stringify(initArr));
                //   let arr = seatData
                let arr = initArr
                //假数据说明：SeatCode座位编号，RowNum-行号，ColumnNum-纵号，YCoord-Y坐标，XCoord-X坐标，Status-状态
                let row = 0
                let col = 0
                let minCol = parseInt(arr[0].XCoord)
                let minRow = parseInt(arr[0].YCoord)
                for (let i of arr) {
                    minRow = parseInt(i.YCoord) < minRow ? parseInt(i.YCoord) : minRow
                    minCol = parseInt(i.XCoord) < minCol ? parseInt(i.XCoord) : minCol
                    row = parseInt(i.YCoord) > row ? parseInt(i.YCoord) : row
                    col = parseInt(i.XCoord) > col ? parseInt(i.XCoord) : col
                }
                this.seatList = arr
                this.seatRow = row - minRow + 1
                this.seatCol = col - minCol + 3
                this.minRow = minRow
                this.minCol = minCol - 1
                this.initSeatArray()
            },
            //初始座位数组
            initSeatArray: function() {
                let seatArray = Array(this.seatRow).fill(0).map(() => Array(this.seatCol).fill({
                    type: -1,
                    SeatCode: '',
                    RowNum: '',
                    ColumnNum: '',
                    flag: '',
                    price: '',
                    name: '',
                    areaId: ''
                }));
                this.seatArray = seatArray
                this.seatSize = this.boxWidth > 0 ?
                    parseInt(parseInt(this.boxWidth, 10) / (this.seatCol + 1), 10) :
                    parseInt(parseInt(414, 10) / (this.seatCol + 1), 10)
                this.initNonSeatPlace();
            },
            //初始化是座位的地方
            initNonSeatPlace: function() {
                let seat = this.seatList.slice()
                let arr = this.seatArray.slice()
                for (let num in seat) {
                    let status = 2 //-1为非座位，0为未购座位，1为已选座位(绿色),2为已购座位(红色)
                    if (seat[num].Status === 0) {
                        status = 0
                    } else if (seat[num].Status === -1) {
                        status = -1
                    }
                    arr[parseInt(seat[num].YCoord) - this.minRow][parseInt(seat[num].XCoord) - this.minCol] = {
                        type: status,
                        SeatCode: seat[num].SeatCode,
                        RowNum: seat[num].RowNum,
                        ColumnNum: seat[num].ColumnNum,
                        flag: seat[num].flag,
                        price: seat[num].price,
                        name: seat[num].name,
                        areaId: seat[num].areaId
                    }
                }
                this.seatArray = arr.slice()

                console.log('this.seatArray111111111111111111')
                console.log(this.seatArray)

                let mArr = []
                for (let i in arr) {
                    let m = ''
                    for (let n of arr[i]) {
                        if (n.SeatCode) {
                            m = n.RowNum
                        }
                    }
                    if (m) {
                        if(this.characterRow===true) m = this.characterData[m-1]
                        mArr.push(m)
                    } else {
                        mArr.push('')
                    }
                }
                this.mArr = mArr
            },
            //放大缩小事件
            onScale: function(e) {
                this.showTis = false
                // this.moveX=-e.detail.x
                let w = this.boxWidth * 0.5
                let s = 1 - e.detail.scale
                this.moveX = w * s
                this.scale = e.detail.scale
                if (s > 0 || s === 0) {
                    this.showTis = true
                }
            },
            //移动事件
            onMove: function(e) {
                this.showTis = false
                this.moveX = e.detail.x
            },
            //重置座位
            resetSeat: function() {
                this.SelectNum = 0
                this.optArr = []
                //将所有已选座位的值变为0
                let oldArray = this.seatArray.slice();
                for (let i = 0; i < this.seatRow; i++) {
                    for (let j = 0; j < this.seatCol; j++) {
                        if (oldArray[i][j].type === 1) {
                            oldArray[i][j].type = 0
                        }
                    }
                }
                this.seatArray = oldArray;
            },
            //选定且购买座位
            async buySeat(){
                if (this.SelectNum === 0) {
                    return
                }
                let oldArray = [];
                for (let i = 0; i < this.seatRow; i++) {
                    for (let j = 0; j < this.seatCol; j++) {
                        if (this.seatArray[i][j].type === 1) {
                            oldArray.push(this.seatArray[i][j].SeatCode)
                        }
                    }
                }

                console.log('座位信息');
                console.log(oldArray);
                if(!this.$user.isLogin()){
                    this.$refs['authorize'].show();
                    return false
                }else if(this.$user.user() && !this.$user.user()['phone']){
                    this.$refs['authorizePhone'].show();
                    return false
                }

                //跳转到订单确认页面
                console.log('跳转到订单确认页面')
                console.log('选中的数组')
                console.log(this.optArr)

                //console.log(this.che)


                await this.createOrder()
            },
            async createOrder(){


                console.log({
                    scheduleId: this.options.sid,
                    seatIds :   this.optArr.map(v=>v.SeatCode).join('|'),
                    seatNames:  this.optArr.map(v=>v.name).join('|'),
                    areaIds  :  this.optArr.map(v=>v.areaId).join('|')
                })

                //创建订单
                let res = await this.$api.orderCreate({
                    scheduleId: this.options.sid,
                    seatIds :   this.optArr.map(v=>v.SeatCode).join('|'),
                    seatNames:  this.optArr.map(v=>v.name).join('|'),
                    areaIds  :  this.optArr.map(v=>v.areaId).join('|')
                })
                this.$tools.goTo('/pages/order/confirm',{orderId:res.data.result.orderId})
            },

            loginOk(data){
                console.log('loginOk')
                console.log('授权登录父组件获取')
                if(!this.$user.user().phone){
                    this.$refs['authorizePhone'].show();
                }else{
                    this.createOrder()
                }

            },
            authorizePhoneOk(){
                console.log('authorizePhoneOk')
                console.log('手机号授权成功之后')
                 this.createOrder()
            },
            //处理座位选择逻辑
            handleChooseSeat: function(row, col) {
                let seatValue = this.seatArray[row][col].type;
                let flag      = this.seatArray[row][col].flag;
                let price     = this.seatArray[row][col].price;

                console.log('this.seatArray[row][col]')
                console.log(this.seatArray);
                console.log('row:'+row+' col:'+col)
                console.log(this.seatArray[row][col])
                console.log('情侣座位判断flag:'+flag)

                if(seatValue === 0 && ((flag===0 && this.SelectNum>=this.maxCanBuy) || (flag>0 && (this.SelectNum+2)>this.maxCanBuy))){
                    this.$tools.msg(`最多只能选择${this.maxCanBuy}个座位`)
                    return false
                }
                let newArray = this.seatArray;
                //如果是已购座位，直接返回
                if (seatValue === 2 || seatValue === -1) return

                //普通座位
                if(flag===0){
                    //如果是已选座位点击后变未选
                    if (seatValue === 1) {
                        newArray[row][col].type = 0
                        this.SelectNum--
                        this.getOptArr(newArray[row][col], 0)
                    } else if (seatValue === 0) {
                        newArray[row][col].type = 1
                        newArray[row][col].columInex = col
                        this.SelectNum++

                        this.getOptArr(newArray[row][col], 1)
                    }
                }else if(flag===1 || flag===2){
                    //console.log('情侣座左边') //右边自动选中 //console.log('情侣座右边') //左边自动选中
                    let nearCol = flag===1 ? col+1 : col-1;
                    if (seatValue === 1) {
                        newArray[row][col].type = 0
                        newArray[row][nearCol].type = 0
                        this.SelectNum -=2
                        this.getOptArr(newArray[row][col], 0)
                        this.getOptArr(newArray[row][nearCol], 0)
                    } else if (seatValue === 0) {
                        newArray[row][col].type          = 1
                        newArray[row][col].columInex     = col
                        newArray[row][nearCol].type      = 1
                        newArray[row][nearCol].columInex = col
                        this.SelectNum +=2
                        this.getOptArr(newArray[row][col], 1)
                        this.getOptArr(newArray[row][nearCol], 1)
                    }
                }

                //必须整体更新二维数组，Vue无法检测到数组某一项更新,必须slice复制一个数组才行
                this.seatArray = newArray.slice();

            },
            //处理已选座位数组
            getOptArr: function(item, type) {
                let optArr = this.optArr
                if (type === 1) {
                    optArr.push(item)
                } else if (type === 0) {
                    let arr = []
                    optArr.forEach(v => {
                        if (v.SeatCode !== item.SeatCode) {
                            arr.push(v)
                        }
                    })
                    optArr = arr
                }
                this.optArr = optArr.slice()
            },
            //切换排期
            changeSchedule(){
                this.$refs['changeScheduleRef'].show();
            },
            changeScheduleConfirm(data){
                this.optArr=[];
                this.SelectNum = 0;
                let {sid,show_date} = data
                this.init(Object.assign(this.options,{sid,show_date}))
            },
            //推荐选座,参数是推荐座位数目，
            smartChoose: function(num) {
                console.log('num===', num)
                // 先重置
                this.resetSeat()
                //找到影院座位水平垂直中间位置的后一排
                let rowStart = parseInt((this.seatRow - 1) / 2, 10) + 1;
                //先从中间排往后排搜索
                let backResult = this.searchSeatByDirection(rowStart, this.seatRow - 1, num);
                if (backResult.length > 0) {
                    this.chooseSeat(backResult);
                    this.SelectNum += num
                    return
                }
                //再从中间排往前排搜索
                let forwardResult = this.searchSeatByDirection(rowStart - 1, 0, num);
                if (forwardResult.length > 0) {
                    this.chooseSeat(forwardResult);
                    this.SelectNum += num
                    return
                }
                //提示用户无合法位置可选
                alert('无合法位置可选!')

            },

            //搜索函数,参数:fromRow起始行，toRow终止行,num推荐座位数
            searchSeatByDirection: function(fromRow, toRow, num) {
                /*
                 * 推荐座位规则
                 * (1)初始状态从座位行数的一半处的后一排的中间开始向左右分别搜索，取离中间最近的，如果满足条件，
                 *    记录下该结果离座位中轴线的距离，后排搜索完成后取距离最小的那个结果座位最终结果，优先向后排进行搜索，
                 *    后排都没有才往前排搜，前排逻辑同上
                 *
                 * (2)只考虑并排且连续的座位，不能不在一排或者一排中间有分隔
                 *
                 * */

                /*
                 * 保存当前方向搜索结果的数组,元素是对象,result是结果数组，offset代表与中轴线的偏移距离
                 * {
                 *   result:Array([x,y])
                 *   offset:Number
                 * }
                 *
                 */
                let currentDirectionSearchResult = [];

                let largeRow = fromRow > toRow ? fromRow : toRow,
                    smallRow = fromRow > toRow ? toRow : fromRow;

                for (let i = smallRow; i <= largeRow; i++) {
                    //每一排的搜索,找出该排里中轴线最近的一组座位
                    let tempRowResult = [],
                        minDistanceToMidLine = Infinity;
                    for (let j = 0; j <= this.seatCol - num; j++) {
                        //如果有合法位置
                        if (this.checkRowSeatContinusAndEmpty(i, j, j + num - 1)) {
                            //计算该组位置距离中轴线的距离:该组位置的中间位置到中轴线的距离
                            let resultMidPos = parseInt((j + num / 2), 10);
                            let distance = Math.abs(parseInt(this.seatCol / 2) - resultMidPos);
                            //如果距离较短则更新
                            if (distance < minDistanceToMidLine) {
                                minDistanceToMidLine = distance;
                                //该行的最终结果
                                tempRowResult = this.generateRowResult(i, j, j + num - 1)
                            }
                        }
                    }
                    //保存该行的最终结果
                    currentDirectionSearchResult.push({
                        result: tempRowResult,
                        offset: minDistanceToMidLine
                    })
                }

                //处理后排的搜索结果:找到距离中轴线最短的一个
                //注意这里的逻辑需要区分前后排，对于后排是从前往后，前排则是从后往前找
                let isBackDir = fromRow < toRow;
                let finalReuslt = [],
                    minDistanceToMid = Infinity;
                if (isBackDir) {
                    //后排情况,从前往后
                    currentDirectionSearchResult.forEach((item) => {
                        if (item.offset < minDistanceToMid) {
                            finalReuslt = item.result;
                            minDistanceToMid = item.offset;
                        }
                    });
                } else {
                    //前排情况，从后往前找
                    currentDirectionSearchResult.reverse().forEach((item) => {
                        if (item.offset < minDistanceToMid) {
                            finalReuslt = item.result;
                            minDistanceToMid = item.offset;
                        }
                    })
                }

                //直接返回结果
                return finalReuslt
            },

            /*辅助函数，判断每一行座位从i列到j列是否全部空余且连续
             *
             */
            checkRowSeatContinusAndEmpty: function(rowNum, startPos, endPos) {
                let isValid = true;
                for (let i = startPos; i <= endPos; i++) {
                    if (this.seatArray[rowNum][i].type !== 0) {
                        isValid = false;
                        break;
                    }
                }
                return isValid
            },
            //辅助函数：返回每一行的某个合理位置的座位数组
            generateRowResult: function(row, startPos, endPos) {
                let result = [];
                for (let i = startPos; i <= endPos; i++) {
                    result.push([row, i])
                }
                return result
            },
            //辅助函数:智能推荐的选座操作
            chooseSeat: function(result) {
                let opt = this.optArr
                let oldArray = this.seatArray.slice();
                for (let i = 0; i < result.length; i++) {
                    //选定座位
                    oldArray[result[i][0]][result[i][1]].type = 1
                    this.optArr.push(oldArray[result[i][0]][result[i][1]])
                }
                this.seatArray = oldArray;
            },
        }
    }
</script>

<style lang="scss" scoped>
    .p-all-10{
        padding: 10rpx;
    }
    .ml-10 {
        margin-left: 10rpx;
    }

    .m-0-10 {
        margin: 0 10rpx;
    }

    .bg-unbtn {
        background-color: #f9abb3;
    }

    .bg-red-1 {
        background-color: #F45664;
    }

    .ml-20 {
        margin-left: 20rpx;
    }

    .mb-20 {
        margin-bottom: 20rpx;
    }

    .p-all-32 {
        padding: 32rpx;
    }

    .fd-cr {
        flex-direction: column-reverse;
        /* 主轴方向从下到上,默认从左到右 */
    }

    .bottom-bar {
        bottom: var(--window-bottom);
    }

    .color-fff {
        color: #fff
    }

    .br-15 {
        border-radius: 15rpx;
    }

    .over-h {
        overflow: hidden;
    }

    .dp-ib {
        display: inline-block;
    }

    .mt-20 {
        margin-top: 20rpx;
    }

    .pa-v-2 {
        /* 定位垂直对齐 */
        left: 50%;
        transform: translateX(-50%)
    }

    .b-d-1 {
        border: 1px dashed #e5e5e5;
    }

    .w-100 {
        width: 100%;
    }

    .h-100 {
        height: 100%;
    }

    .bg-f1 {
        background-color: #f1f1f1;
    }

    .h-100vh {
        height: 100vh;
    }

    .pt-f {
        position: fixed;
    }

    .left-0 {
        left: 0;
    }

    .p-0-32 {
        padding: 0 32rpx;
    }

    .pt-20 {
        padding-top: 20rpx;
    }

    .bg-white {
        background-color: #fff;
    }

    .z1000 {
        z-index: 1000;
    }

    .fz-34 {
        font-size: 34rpx;
    }

    .fw-b {
        font-weight: bold;
    }

    .mt-10 {
        margin-top: 10rpx;
    }

    .fz-28 {
        font-size: 28rpx;
    }

    .color-666 {
        color: #666666
    }

    .dp-f {
        display: flex;
    }

    .jc-c {
        justify-content: center;
    }

    .ai-c {
        align-items: center;
    }

    .fz-22 {
        font-size: 22rpx;
    }

    .color-333 {
        color: #333333
    }

    .m-0-a {
        margin: 0 auto;
    }

    .mt-48 {
        margin-top: 48rpx;
    }

    .fz-20 {
        font-size: 20rpx;
    }

    .color-999 {
        color: #999999
    }

    .b-1 {
        border: 1px solid #CCCCCC;
    }

    .br-5 {
        border-radius: 5rpx;
    }

    .Stage {
        background-color: #dddddd;
        width: 380rpx;
        height: 34rpx;
        transform: perspective(34rpx) rotateX(-10deg);
        margin: 0 auto;
    }

    .bg-line {
        background-color: rgba(0, 0, 0, 0.3);
    }

    .sel-seat {
        background: url('https://un-1303693589.cos.ap-nanjing.myqcloud.com/miniprogram/selected_1.png') center center no-repeat;
        background-size: 100% 100%;
    }

    .unsel-seat {
        background: url('https://un-1303693589.cos.ap-nanjing.myqcloud.com/miniprogram/unselected_1.png') center center no-repeat;
        background-size: 100% 100%;
    }

    .bought-seat {
        background: url('https://un-1303693589.cos.ap-nanjing.myqcloud.com/miniprogram/bought_1.png') center center no-repeat;
        background-size: 100% 100%;
    }
</style>
